package cn.com.checne.controller.front;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import cn.com.checne.constants.Constants;
import cn.com.checne.dao.JobCategoryDao;
import cn.com.checne.dao.JobDeptDao;
import cn.com.checne.dao.JobInfoDao;
import cn.com.checne.dao.JobNewsInfoDao;
import cn.com.checne.dao.ResumeInfoDao;
import cn.com.checne.model.domain.JobCategory;
import cn.com.checne.model.domain.JobDept;
import cn.com.checne.model.domain.JobInfo;
import cn.com.checne.model.domain.JobNewsInfo;
import cn.com.checne.model.domain.ResumeCertificateInfo;
import cn.com.checne.model.domain.ResumeEducationInfo;
import cn.com.checne.model.domain.ResumeFamilyInfo;
import cn.com.checne.model.domain.ResumeInfo;
import cn.com.checne.model.domain.ResumeTrainInfo;
import cn.com.checne.model.domain.ResumeWorkInfo;
import cn.com.checne.model.dto.JobNewsQuery;
import cn.com.checne.model.dto.JobQuery;
import cn.com.checne.util.FileUtils;
import cn.com.checne.util.HeaderUtils;
import cn.com.checne.util.LanguageUtils;
import cn.com.checne.util.PageBean;
import cn.com.checne.util.WebUtils;

@Controller
public class HRFrontController {
	protected static final Logger logger = Logger.getLogger(HRFrontController.class);

	@Resource
	private JobCategoryDao cateDao;
	@Resource
	private JobNewsInfoDao jobNewsDao;
	@Resource
	private JobDeptDao jobDeptDao ;
	@Resource
	private JobInfoDao jobDao;
	@Resource
	private ResumeInfoDao resumeDao ;
	@Resource
	private List<String> allowedUploadImages ;

	//首页面
	@RequestMapping(value="/{lg}/hr",method=RequestMethod.GET)
	public ModelAndView index(
			@PathVariable String lg,
			@RequestParam(value = "cateId", required = false, defaultValue = "0") String cId,
			@RequestParam(value = "curPage", required = false, defaultValue = "1") String pg,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		
		ModelAndView mav = new ModelAndView();
		lg = StringUtils.isBlank(lg) ? Constants.LANGUAGE_CN : lg ;
		String viewName = "front/" + lg + "/hr-list" ;
		int languageId = LanguageUtils.getLanguage(lg);
		int cateId = Integer.parseInt(cId);
		int curPage = Integer.parseInt(pg);
		List<JobCategory> cateList = cateDao.getAll(languageId, -1);
		JobCategory cate = new JobCategory() ;
		if(cateId == 0){
			if(cateList != null && cateList.size() > 0){
				cate = cateList.get(0);
			}
		}else{
			cate = cateDao.getJobCategory(cateId);
		}

		JobNewsQuery query = new JobNewsQuery();
		query.setLanguageId(languageId);
		query.setCateId(cate.getCateId());
		query.setIsShowList(1);
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(curPage);
		List<JobNewsInfo> jobNewsList = jobNewsDao.getJobNewsListByCondition(query, pageBean.getStart(), pageBean.getRowsPerPage());
		pageBean.setMaxRowCount(jobNewsDao.getJobNewsCountByCondition(query));
		pageBean.setMaxPage();
		pageBean.setPageNoList();

		JobNewsInfo jobNewsInfo = new JobNewsInfo();
		if(cate.getShowType() == 0 ){ //直接显示详情
			jobNewsInfo = (jobNewsList != null && jobNewsList.size() > 0 ) ? jobNewsList.get(0) : jobNewsInfo ;
		}
	    
		modelMap.put("cateList", cateList);
		modelMap.put("jobNewsList", jobNewsList);
		modelMap.put("jobNews", jobNewsInfo);
		modelMap.put("cate", cate);
		modelMap.put("pageBean", pageBean);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//详情页面
	@RequestMapping(value="/{lg}/hr/{jobNewsId}",method=RequestMethod.GET)
	public ModelAndView detail(
			@PathVariable String lg,
			@PathVariable int jobNewsId,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		String message = "" ;
		ModelAndView mav = new ModelAndView();
		String viewName = "front/" + lg + "/hr-detail" ;
		
		int languageId = LanguageUtils.getLanguage(lg);
		List<JobCategory> cateList = cateDao.getAll(languageId, -1);
		JobNewsInfo jobNews = jobNewsDao.getJobById(jobNewsId);
		
		modelMap.put("cateList", cateList);
		modelMap.put("jobNews", jobNews);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//JobList
	@RequestMapping(value="/{lg}/job",method=RequestMethod.GET)
	public ModelAndView jobList(
			@PathVariable String lg,
			@RequestParam(value = "cateId", required = false, defaultValue = "0") String cId,
			@RequestParam(value = "deptId", required = false, defaultValue = "0") String dptId,
			@RequestParam(value = "curPage", required = false, defaultValue = "1") String pg,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		ModelAndView mav = new ModelAndView();
		lg = StringUtils.isBlank(lg) ? Constants.LANGUAGE_CN : lg ;
		String viewName = "front/" + lg + "/job-list" ;
		int languageId = LanguageUtils.getLanguage(lg);
		int cateId = Integer.parseInt(cId);
		int deptId = Integer.parseInt(dptId);
		int curPage = Integer.parseInt(pg);
		List<JobCategory> cateList = cateDao.getAll(languageId, -1);
		List<JobDept> deptList = jobDeptDao.getAll(languageId);

		JobQuery query = new JobQuery();
		query.setLanguageId(languageId);
		query.setCateId(cateId);
		query.setDeptId(deptId);
		PageBean pageBean = new PageBean();
		pageBean.setCurPage(curPage);
		List<JobInfo> jobList = jobDao.getJobListByCondition(query, pageBean.getStart(), pageBean.getRowsPerPage());
		pageBean.setMaxRowCount(jobDao.getJobCountByCondition(query));
		pageBean.setMaxPage();
		pageBean.setPageNoList();

		JobCategory cate = cateDao.getJobCategory(cateId);
	    
		modelMap.put("cateList", cateList);
		modelMap.put("jobList", jobList);
		modelMap.put("deptList", deptList);
		modelMap.put("cate", cate);
		modelMap.put("deptId", deptId);
		modelMap.put("pageBean", pageBean);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//jobDetail
	@RequestMapping(value="/{lg}/job/{cateId}/{jobId}",method=RequestMethod.GET)
	public ModelAndView jobDetail(
			@PathVariable String lg,
			@PathVariable int cateId,
			@PathVariable int jobId,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		
		ModelAndView mav = new ModelAndView();
		String viewName = "front/" + lg + "/job-detail" ;
		
		int languageId = LanguageUtils.getLanguage(lg);
		List<JobCategory> cateList = cateDao.getAll(languageId,-1);
		JobCategory cate = cateDao.getJobCategory(cateId);
		JobInfo job = jobDao.getJobById(jobId);
		
		modelMap.put("cateList", cateList);
		modelMap.put("cate", cate);
		modelMap.put("job", job);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	
	//jobDetail
	@RequestMapping(value="/{lg}/job/apply/{cateId}/{jobId}",method=RequestMethod.GET)
	public ModelAndView showApply(
			@PathVariable String lg,
			@PathVariable int cateId,
			@PathVariable int jobId,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		
		ModelAndView mav = new ModelAndView();
		String viewName = "front/" + lg + "/job-apply" ;
		
		int languageId = LanguageUtils.getLanguage(lg);
		List<JobCategory> cateList = cateDao.getAll(languageId,-1);
		JobCategory cate = cateDao.getJobCategory(cateId);
		JobInfo job = jobDao.getJobById(jobId);
		ResumeInfo resume = new ResumeInfo();
		modelMap.put("cateList", cateList);
		modelMap.put("cate", cate);
		modelMap.put("job", job);
		modelMap.put("resume", resume);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	//jobApply-form
	@SuppressWarnings("deprecation")
	@RequestMapping(value="/{lg}/job-apply/{cateId}/{jobId}",method=RequestMethod.POST)
	public ModelAndView jobApply(
			@PathVariable String lg,
			@PathVariable int cateId,
			@PathVariable int jobId,
			HttpServletRequest request,HttpServletResponse response, ModelMap modelMap) throws Exception {
		
		StringBuffer message = new StringBuffer();
		message.append("<br/>");
		boolean result = false ;

		ModelAndView mav = new ModelAndView();
		String viewName = "front/" + lg + "/job-apply-result" ;
		
		int languageId = LanguageUtils.getLanguage(lg);
		List<JobCategory> cateList = cateDao.getAll(languageId,-1);
		JobCategory cate = cateDao.getJobCategory(cateId);
		JobInfo job = jobDao.getJobById(jobId);
		
		modelMap.put("cate", cate);
		modelMap.put("job", job);
		modelMap.put("cateList", cateList);
		
		ResumeInfo resume = new ResumeInfo();

		// 图片上传
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile multipartFile = multipartRequest.getFile("image");
		if(multipartFile != null){
			String originalFilename = multipartFile.getOriginalFilename();
			if(StringUtils.isNotBlank(originalFilename)){
				if (!isAllowed(originalFilename)) {
					message.append("上传文件类型不符合,必须是以下几种" + this.allowedUploadImages.toString() + "<br/>");
				}else{
					String fileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
							+ "." + FilenameUtils.getExtension(originalFilename);
					String basePath = request.getRealPath("/") + "/";
					String relativePath = "userfiles/upload/user-images/"
							+ DateFormatUtils.format(new Date(), "yyyy-MM-dd").replaceAll(
									"-", "/") + "/";
					FileUtils.mkdirs(basePath + relativePath);
					multipartFile.transferTo(new File(basePath + relativePath + fileName));
					resume.setImage(relativePath + fileName);
				}
			}
		}
		
		
		
		String resumeId = UUID.randomUUID().toString().replaceAll("-", "");
		String name = WebUtils.getRequestParameterAsStringEscape(request, "name");
		if(StringUtils.isBlank(name)){
			message.append("姓名不能为空.<br/>");
		}
		String birthday = WebUtils.getRequestParameterAsStringEscape(request, "birthday");
		if(StringUtils.isBlank(birthday)){
			message.append("出生日期不能为空.<br/>");
		}
		String gender = WebUtils.getRequestParameterAsStringEscape(request, "gender");
		if(StringUtils.isBlank(gender)){
			message.append("性别不能为空.<br/>");
		}
		gender = StringUtils.isNotBlank(gender) ? gender : "1" ;
		String politicsStatus = WebUtils.getRequestParameterAsStringEscape(request, "politicsStatus");
		if(StringUtils.isBlank(politicsStatus)){
			message.append("政治面貌不能为空.<br/>");
		}
		politicsStatus = StringUtils.isNotBlank(politicsStatus) ? politicsStatus : "1" ;
		String nation = WebUtils.getRequestParameterAsStringEscape(request, "nation");
		if(StringUtils.isBlank(nation)){
			message.append("民族不能为空.<br/>");
		}
		String marriageStatus = WebUtils.getRequestParameterAsStringEscape(request, "marriageStatus");
		if(StringUtils.isBlank(marriageStatus)){
			message.append("婚姻状况不能为空.<br/>");
		}
		marriageStatus = StringUtils.isNotBlank(marriageStatus) ? marriageStatus : "0" ;
		String bearStatus = WebUtils.getRequestParameterAsStringEscape(request, "bearStatus");
		if(StringUtils.isBlank(bearStatus)){
			message.append("生育状况不能为空.<br/>");
		}
		String height = WebUtils.getRequestParameterAsStringEscape(request, "height");
		height = StringUtils.isNotBlank(height) ? height : "0" ;
		String email = WebUtils.getRequestParameterAsStringEscape(request, "email");
		if(StringUtils.isBlank(email)){
			message.append("电子 邮箱不能为空.<br/>");
		}
		String areaCode = WebUtils.getRequestParameterAsStringEscape(request, "areaCode");
		String telephone = WebUtils.getRequestParameterAsStringEscape(request, "telephone");
		if(StringUtils.isBlank(bearStatus)){
			message.append("固定电话不能为空.<br/>");
		}
		
		resume.setLanguageId(languageId);
		resume.setJobId(jobId);
		resume.setResumeId(resumeId);
		resume.setName(name);
		resume.setBirthday(birthday);
		resume.setGender(Integer.parseInt(gender));
		resume.setPoliticsStatus(Integer.parseInt(politicsStatus));
		resume.setNation(nation);
		resume.setMarriageStatus(Integer.parseInt(marriageStatus));
		resume.setBearStatus(bearStatus);
		resume.setHeight(!height.matches("\\d+") ? 0 : Integer.parseInt(height));
		resume.setEmail(email);
		resume.setAreaCode(areaCode);
		resume.setTelephone(telephone);
		
		
		//教育经历
		String edStarts [] = request.getParameterValues("edStart");
		String edEnds [] = request.getParameterValues("edEnd");
		String edSchools [] = request.getParameterValues("edSchool");
		String edProfessions [] = request.getParameterValues("edProfession");
		String edBackgrounds [] = request.getParameterValues("edBackground");
		String edEgrees [] = request.getParameterValues("edEgree");
		String edCategorys [] = request.getParameterValues("edCategory");
		int edLen = edStarts != null ? edStarts.length : 0 ;
		List<ResumeEducationInfo> edList = new ArrayList<ResumeEducationInfo>();
		for(int i = 0 ; i < edLen ; i ++){
			ResumeEducationInfo ed = new ResumeEducationInfo();
			if(StringUtils.isNotBlank(edStarts[i]) || StringUtils.isNotBlank(edEnds[i]) || StringUtils.isNotBlank(edSchools[i])
					|| StringUtils.isNotBlank(edProfessions[i]) || StringUtils.isNotBlank(edBackgrounds[i]) ||StringUtils.isNotBlank(edEgrees[i]) 
					|| StringUtils.isNotBlank(edCategorys[i])){
				
				ed.setStart(edStarts[i]);
				ed.setEnd(edEnds[i]);
				ed.setSchool(edSchools[i]);
				ed.setProfession(edProfessions[i]);
				ed.setBackground(edBackgrounds[i]);
				ed.setEgree(edEgrees[i]);
				ed.setCategory(edCategorys[i]);
				ed.setResumeId(resumeId);
				edList.add(ed);
			}
		}
		resume.setResumeEducationList(edList);
		
		if(edList == null || edList.size() == 0){
			message.append("教育经历不能为空.<br/>");
		}
		
		//工作经历
		String wkStarts [] = request.getParameterValues("wkStart");
		String wkEnds [] = request.getParameterValues("wkEnd");
		String wkCompanys [] = request.getParameterValues("wkCompany");
		String wkStations [] = request.getParameterValues("wkStation");
		String wkProvePersons [] = request.getParameterValues("wkProvePerson");
		String wkContacts [] = request.getParameterValues("wkContact");
		String wkResponsibilitys [] = request.getParameterValues("wkResponsibility");
		String wkLeaveReasons [] = request.getParameterValues("wkLeaveReason");

		int wkLen = wkStarts != null ? wkStarts.length : 0 ;
		List<ResumeWorkInfo> wkList = new ArrayList<ResumeWorkInfo>();
		for(int i = 0 ; i < wkLen ; i ++){
			ResumeWorkInfo wk = new ResumeWorkInfo();
			if(StringUtils.isNotBlank(wkStarts[i]) || StringUtils.isNotBlank(wkEnds[i]) || StringUtils.isNotBlank(wkCompanys[i])
					|| StringUtils.isNotBlank(wkStations[i]) || StringUtils.isNotBlank(wkProvePersons[i]) ||StringUtils.isNotBlank(wkContacts[i]) 
					|| StringUtils.isNotBlank(wkResponsibilitys[i]) || StringUtils.isNotBlank(wkLeaveReasons[i])){
				
				wk.setStart(wkStarts[i]);
				wk.setEnd(wkEnds[i]);
				wk.setCompany(wkCompanys[i]);
				wk.setStation(wkStations[i]);
				wk.setProvePerson(wkProvePersons[i]);
				wk.setContact(wkContacts[i]);
				wk.setResponsibility(wkResponsibilitys[i]);
				wk.setLeaveReason(wkLeaveReasons[i]);
				wk.setResumeId(resumeId);
				wkList.add(wk);
			}
		}
		resume.setResumeWorkList(wkList);
		if(wkList == null || wkList.size() == 0){
			message.append("工作经历不能为空.<br/>");
		}
		//证书
		String cfTimes [] = request.getParameterValues("cfTime");
		String cfCompanys [] = request.getParameterValues("cfCompany");
		String cfNames [] = request.getParameterValues("cfName");

		int cfLen = cfTimes != null ? cfTimes.length : 0 ;
		List<ResumeCertificateInfo> cfList = new ArrayList<ResumeCertificateInfo>();
		for(int i = 0 ; i < cfLen ; i ++){
			ResumeCertificateInfo cf = new ResumeCertificateInfo();
			if(StringUtils.isNotBlank(cfTimes[i]) || StringUtils.isNotBlank(cfCompanys[i]) || StringUtils.isNotBlank(cfNames[i])){
				cf.setTime(cfTimes[i]);
				cf.setCompany(cfCompanys[i]);
				cf.setName(cfNames[i]);
				cf.setResumeId(resumeId);
				cfList.add(cf);
			}
		}
		resume.setResumeCertificaeList(cfList);
		
		//培训机构
		String trStarts [] = request.getParameterValues("trStart");
		String trEnds [] = request.getParameterValues("trEnd");
		String trCompanys [] = request.getParameterValues("trCompany");
		String trContents [] = request.getParameterValues("trContent");

		int trLen = trStarts != null ? trStarts.length : 0 ;
		List<ResumeTrainInfo> trList = new ArrayList<ResumeTrainInfo>();
		for(int i = 0 ; i < trLen ; i ++){
			ResumeTrainInfo tr = new ResumeTrainInfo();
			if(StringUtils.isNotBlank(trStarts[i]) || StringUtils.isNotBlank(trEnds[i]) 
					|| StringUtils.isNotBlank(trCompanys[i]) || StringUtils.isNotBlank(trContents[i])){
				tr.setStart(trStarts[i]);
				tr.setEnd(trEnds[i]);
				tr.setCompany(trCompanys[i]);
				tr.setContent(trContents[i]);
				tr.setResumeId(resumeId);
				trList.add(tr);
			}
		}
		resume.setResumeTrainList(trList);
		
		//家庭情况
		String faNames [] = request.getParameterValues("faName");
		String faRelations [] = request.getParameterValues("faRelation");
		String faCompanys [] = request.getParameterValues("faCompany");
		String faStations [] = request.getParameterValues("faStation");

		int faLen = faNames != null ? faNames.length : 0 ;
		List<ResumeFamilyInfo> faList = new ArrayList<ResumeFamilyInfo>();
		for(int i = 0 ; i < faLen ; i ++){
			ResumeFamilyInfo fa = new ResumeFamilyInfo();
			if(StringUtils.isNotBlank(faNames[i]) || StringUtils.isNotBlank(faRelations[i]) 
					|| StringUtils.isNotBlank(faCompanys[i]) || StringUtils.isNotBlank(faStations[i])){
				fa.setName(faNames[i]);
				fa.setRelation(faRelations[i]);
				fa.setCompany(faCompanys[i]);
				fa.setStation(faStations[i]);
				fa.setResumeId(resumeId);
				faList.add(fa);
			}
		}
		resume.setResumeFamilyList(faList);
		
		//业绩
		String performance = WebUtils.getRequestParameterAsStringEscape(request, "performance");
		//奖罚经历
		String rewardsPunishment = WebUtils.getRequestParameterAsStringEscape(request, "rewardsPunishment");
		//未处理事项
		String unHandleThing = WebUtils.getRequestParameterAsStringEscape(request, "unHandleThing");
		//职业生涯规划
		String careerPlanning = WebUtils.getRequestParameterAsStringEscape(request, "careerPlanning");
		//个人简介
		String personalHobbies = WebUtils.getRequestParameterAsStringEscape(request, "personalHobbies");
		
		resume.setPerformance(performance);
		resume.setRewardsPunishment(rewardsPunishment);
		resume.setUnHandleThing(StringUtils.isNotBlank(unHandleThing) ? Integer.parseInt(unHandleThing) : 0);
		resume.setCareerPlanning(careerPlanning);
		resume.setPersonalHobbies(personalHobbies);
		
		if(message.length() > 5 ){
			modelMap.put("message", message.toString());
			modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
			modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
			mav.addAllObjects(modelMap);
			mav.setViewName(viewName);
			return mav ;
		}
		
		result = resumeDao.create(resume);
		modelMap.put("resume", resume);
		modelMap.put("result", result);
		modelMap.addAllAttributes(LanguageUtils.getModelMap(lg));
		modelMap.addAllAttributes(HeaderUtils.getHeaderMap(languageId));
		mav.setViewName(viewName);
		mav.addAllObjects(modelMap);
		return mav ;
	}
	
	public boolean isAllowed(String fileName) {
		for (String suffix : this.allowedUploadImages) {
			if (StringUtils.equalsIgnoreCase(suffix,
					FilenameUtils.getExtension(fileName))) {
				return true;
			}
		}
		return false;
	}
}